package mipo.top.admin.service.impl;

import mipo.top.base.util.PageUtil;
import mipo.top.admin.domain.Department;
import mipo.top.admin.mapper.DepartmentMapper;
import mipo.top.admin.query.DepartmentQuery;
import mipo.top.admin.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceimpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    public List<Department> findall() {
        return departmentMapper.findall();
    }

    public Department findByid(Long id) {
        return departmentMapper.findByid(id);
    }

    public void insert(Department department) {
        departmentMapper.insert(department);
    }

    public void updata(Department department) {
        departmentMapper.updata(department);
    }

    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    public PageUtil<Department> queryDate(DepartmentQuery query) {
        Integer count = departmentMapper.count(query);
        List<Department> departments = departmentMapper.queryDate(query);
        return new PageUtil<Department>(count,departments);
    }

    public void bacthDel(List<Long> ids) {
        departmentMapper.bacthDel(ids);
    }

    public List<Department> deptTree() {
        List<Department> alldept = departmentMapper.findall();
        Map<Long, Department> map = alldept.stream().collect(Collectors.toMap(Department::getId, e -> e));
        List<Department> treeData = new ArrayList<>();
        for (Department department : alldept) {
            if(department.getParentId()== null){
                treeData.add(department);
            }else {
                ;
                Department sd = map.get(department.getParentId());
                if(sd != null) {
                    sd.getChildren().add(department);
                }
            }
        }
        return treeData;

    }
}
